package com.weirdor.boot.admin.www.common;

import com.weirdor.boot.common.annotation.SysLog;
import com.weirdor.boot.common.utils.R;
import com.weirdor.boot.module.entity.SysUser;
import com.weirdor.boot.module.service.ISysUserService;
import com.weirdor.boot.module.service.ISysUserTokenService;
import com.weirdor.boot.module.utils.ShiroUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 */
@RestController
@RequestMapping("/api")
public class SysLoginController extends AbstractController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserTokenService sysUserTokenService;
    /**
     * 登录
     */

    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public Map<String, Object> login(HttpServletRequest request, String username, String password) throws IOException {
        SysUser user = sysUserService.queryByUserName(username);

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(ShiroUtils.sha256(password, user.getSalt()))) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());
        return r;
    }

    /**
     * 退出
     */
    @SysLog("用户退出")
    @RequestMapping(value = "/sys/logout", method = RequestMethod.POST)
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }
}